<?php

namespace app\admin\model;

use app\admin\model\article\Article;
use app\admin\model\article\Message;
use app\admin\model\course\Course;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\UserLevelLog;
use fast\Random;
use think\Model;
use think\Validate;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text'
    ];

    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });

//
//        self::beforeUpdate(function ($row) {
//            $changedata = $row->getChangedData();
//            $origin = $row->getOriginData();
//            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
//                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
//            }
//            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
//                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
//            }
//        });
    }
    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $userId 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $userId, $type, $fromType, $memo)
    {
        $user = self::lock(true)->find($userId);
        if ($user && $money != 0) {
            switch ($type){
                case MoneyLog::MONEY:
                    $typeName = "余额";
                    $before = $user->money;
                    $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                    break;
                case MoneyLog::SCORE:
                    $typeName = "积分";
                    $before = $user->score;
                    $after = function_exists('bcadd') ? bcadd($user->score, $money, 2) : $user->score + $money;
                    break;
                default: //默认走余额
                    $typeName = "余额";
                    $before = $user->money;
                    $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
            }
            if($after < 0) {
                exception($typeName . "不足");
            }

            switch ($type){
                case MoneyLog::MONEY:
                    $user->save(['money' => $after]);
                    break;
                case MoneyLog::SCORE:
                    $user->save(['score' => $after]);
                    break;
                default: //默认走余额
                    $user->save(['money' => $after]);
            }
            //写入日志
            $symbol = $money > 0 ? $symbol = 1 : $symbol = 2;
            //写入日志
            MoneyLog::create(['user_id' => $user['id'], 'money' => $money, 'before' => $before,'after' => $after, 'memo' => $memo, 'type' => $type, 'from_type'=>$fromType, "symbol"=>$symbol]);
            return (int)$after;
        }

    }

    /*
        * 添加老师
        * */
    public function addTeacher($param){
        $validate = new Validate([
            ["username","require","账户必填"],
            ["nickname","require","姓名必填"],
            ['mobile','max:11|/^1[3-9]{1}[0-9]{9}$/','联系电话最多不能超过11个字符|手机号码格式不正确'],
            ["password","require","密码必填"],
        ]);

        $result = $validate->check($param);
        if(!$result){
            exception((string)$validate->getError());
        }
//        $findMobile = $this->where("mobile",$param['mobile'])->where("user_type",2)->find();
//        if($findMobile){
//            exception("联系电话已存在");
//        }
        $findUserName = $this->where("username",$param['username'])->where("user_type",2)->find();
        if($findUserName){
            exception("账号已存在");
        }
        $salt = \fast\Random::alnum();
        $param['password'] = \app\common\library\Auth::instance()->getEncryptPassword($param['password'], $salt);
        $param['salt'] = $salt;
        $this->save($param);
        return true;
    }


    public function editTeacher($param){
        $validate = new Validate([
            ["username","require","账户必填"],
            ["nickname","require","姓名必填"],
            ['mobile','max:11|/^1[3-9]{1}[0-9]{9}$/','联系电话最多不能超过11个字符|手机号码格式不正确'],

        ]);

        $result = $validate->check($param);
        if(!$result){
            exception((string)$validate->getError());
        }
//        $findMobile = $this->where("mobile",$param['mobile'])->where("user_type",2)->find();
//        if($findMobile){
//            exception("联系电话已存在");
//        }
        $findUserName = $this->where("username",$param['username'])
            ->where("id","<>",$this->id)
            ->where("user_type",2)->find();
        if($findUserName){
            exception("账号已存在");
        }

        $this->save($param);
        return true;
    }
    public function changeVip($is_vip, $order_id){
        //修改用户等级
        $this->is_vip = $is_vip;
        $this->save();
        //发消息
        $messageModel = new Message();
        $articleModel = new Article();
        $messageModel->addUserMessage([
            "user_id" => $this->id,
            "type" => $articleModel::TYPE_BUY_VIP,
            "data_id" => $order_id,
            "title" => '购买Vip成功',
            "des" => '购买Vip成功',
        ]);


    }


    public static function getWechatUrl($course_id = 0){
        $wechat_uesr_id = 0;
        if($course_id > 0 ){
            $wechat_uesr_id = Course::where("id",$course_id)->value("wechat_uesr_id")??0;
        }
        $where = [
            "user_type" => 2,
            "kefu_show" => 1,
        ];
        if($wechat_uesr_id > 0){
            $where = [
                "id"=>$wechat_uesr_id
            ];
        }

//        dump($where);exit;
        return self::where($where)
            ->orderRaw("rand()")
            ->where("wechat_url","<>","")->value("wechat_url");
    }

}
